<?php

use Illuminate\Database\Eloquent\Model;

class categoryModel extends Model
{
    protected $table = 'category';
    protected $primaryKey = 'id';

    protected static $HONGBAOCODE = 1;
    protected static $QUANYICODE = 2;

    protected function serializeDate($date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public static function getCategoryIds($id)
    {
        $categoryIds = self::recursionGetCategoryIds($id);
        return $categoryIds;
    }

    public static function getSpecialShowArray()
    {
        return [
            [
                'name'=>'兑换券换购',
                'code'=>self::$HONGBAOCODE
            ],[
                'name'=>'消费补贴换购',
                'code'=>self::$QUANYICODE
            ],
        ];
    }

    public static function getHongbaoCode()
    {
        return self::$HONGBAOCODE;
    }

    public static function getQuanyiCode()
    {
        return self::$QUANYICODE;
    }

    public static function recursionGetCategoryIds($id)
    {
        $ids = [];
        $category_ids = self::where('pid', $id)->where('status', 'normal')->pluck('id');
        if ($category_ids) {
            foreach ($category_ids as $k => $v) {
                $childrenCategoryIds = self::recursionGetCategoryIds($v);
                if ($childrenCategoryIds && count($childrenCategoryIds) > 0) $ids = array_merge($ids, $childrenCategoryIds);
            }
        }
        return array_merge($ids, [intval($id)]);
    }

    public static function getChildCategoryIds($id, $in = false)
    {
        $ids = [];
        $category_ids = self::where('pid', $id)->pluck('id');
        if ($category_ids) {
            foreach ($category_ids as $k => $v) {
                $childrenCategoryIds = self::getChildCategoryIds($v, true);
                if ($childrenCategoryIds && count($childrenCategoryIds) > 0) $ids = array_merge($ids, $childrenCategoryIds);
            }
        }
        if($in){
            return array_merge($ids, [intval($id)]);
        }
        return $ids;
    }

    public static function getCategoryDetail($id)
    {
        if ($id) {
            $category = self::where(['id' => $id, 'status' => 'normal'])->first();
        } else {
            // 没有 id
            $category = self::where(['pid' => 0, 'status' => 'normal'])
                ->orderBy('weigh', 'desc')
                ->orderBy('id', 'desc')
                ->first();
        }
        return $category;
    }

    public static function getCategoryList($id)
    {
        $category = self::where(['status' => 'normal'])->get()->toArray();
        $tree_data = get_tree($category);
        foreach ($tree_data as $branch) {
            if ($id == $branch['id']) {
                return $branch;
            }
        }
        return $tree_data;
    }
}
